<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/home' }">活动管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/home' }">活动列表</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/home' }">活动详情</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 搜索与添加信息 -->
        <el-card>
            <el-row :gutter="15">
                <el-col :span="8">
                    <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>

                <el-col :span="4">
                        <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
                          <el-dialog title="添加用户" width="500px" :visible.sync="dialogFormVisible">
                            <el-form ref="addFormRef" :model="form"  :rules="addFormRules" label-width="60px">
                              <el-form-item label="姓名" prop="username">
                                <el-input v-model="form.username" prefix-icon = "el-icon-s-custom" autocomplete="off"></el-input>
                              </el-form-item>
                              <el-form-item label="密码" prop="password">
                                <el-input v-model="form.password" prefix-icon = "el-icon-key" autocomplete="off"></el-input>
                              </el-form-item>
                              <el-form-item label="邮箱" prop="email">
                                <el-input v-model="form.email" prefix-icon = "el-icon-message" autocomplete="off"></el-input>
                              </el-form-item>
                              <el-form-item label="电话" prop="mobile">
                                <el-input v-model="form.mobile" prefix-icon = "el-icon-mobile-phone" autocomplete="off"></el-input>
                              </el-form-item>
                            </el-form>
                            <div slot="footer" class="dialog-footer">
                              <el-button @click="dialogFormVisible = false">取 消</el-button>
                              <el-button type="primary" @click="addUser">确 定</el-button>
                            </div>
                          </el-dialog>
                </el-col>
            </el-row>
        </el-card>
        <!-- 表格 -->
        <!-- 
            当el-table元素中注入data对象数组后，在el-table-column中用prop属性来对应对象中的键名即可填入数据，
            用label属性来定义表格的列名。可以使用width属性来定义列宽。
         -->
        <el-table
        :data="userList"
        style="width: 100%"
        border
        stripe>
            <el-table-column
                type="index"
                label="编号"
                width="50px">
            </el-table-column>
            <el-table-column
                prop="username"
                label="姓名">
            </el-table-column>
            <el-table-column
                prop="email"
                label="邮箱">
            </el-table-column>
            <el-table-column
                prop="mobile"
                label="电话">
            </el-table-column>
            <el-table-column
                prop="role_name"
                label="角色">
            </el-table-column>
            <el-table-column
                label="状态">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChanged(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column
            label="操作" width="200px">
            <template slot-scope="scope">
                <el-tooltip effect="dark" content="修改" placement="right-end" :enterable="false">
                  <el-button type="primary" icon="el-icon-edit" size="mini" ></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="删除" placement="right-end" :enterable="false">
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(scope.row.id)"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="角色" placement="right-end" :enterable="false">
                  <el-button type="info" icon="el-icon-user" size="mini"></el-button>
                </el-tooltip>
              </template>
            </el-table-column> 
        </el-table>
         <!-- 分页组件 -->
            <!-- 
                size-change	pageSize 改变时会触发	每页条数
                current-change	currentPage 改变时会触发	当前页
                page-size	每页显示条目个数，支持 .sync 修饰符	number	—	10
                total	总条目数	number	—	—
             -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>     
    </div>
</template>

<script>
    export default {
      data() {
          var checkMobile = (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(value)) && value) {
            return callback(new Error('请输入正确的电话号码'));
          } else {
                callback();
          }
        };
        return {
          //查询用户信息的参数
          queryInfo: {
              query:'',
              pagenum:1,
              pagesize:5
          },
          //保存请求服务端数据(用户的列表)
          userList:[],
          //总记录数
          total:0,
          dialogFormVisible: false,
          form: {
            username:'',
            password:'',
            email:'',
            mobile:''
          },
          //这里是表单难的规则对象
            addFormRules:{
                // 验证用户名是否合法
                username: [
                    { required: true, message: '请输入登录名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                // 验证密码是否合法
                password:[
                    { required: true, message: '请输入登录密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                mobile:[
                    { validator: checkMobile, trigger: 'blur' }
                ]
            }
        }
      },
      created(){
          this.getUserList()
      },
      methods:{
          //获取用户列表数据
         async getUserList(){
            //利用axios发送请求获取到用户数据,params表示参数   http://127.0.0.1/项目名/users?query=""&pagenum=1&pagesize=2
            const {data:res} = await this.$axios.get('users',{params:this.queryInfo})
            if(res.meta.status !=200) {
                return this.$message.error("数据获取失败");
            }
            //获取数据并赋值给userList
            this.userList = res.data.users
            this.total = res.data.total
            console.log(res)
          },
          //监听pagesize的改变事件   
          handleSizeChange(newSize){
            this.queryInfo.pagesize=newSize
            this.getUserList() 

          },
          //监听页码改变的事件
          handleCurrentChange(newPage) {
            this.queryInfo.pagenum=newPage
            this.getUserList() 
          },
          userStateChanged(userinfo){
            console.log(userinfo);
          },
          //监听switch开关的状态   
          async userStateChanged(userinfo){
             //console.log(userinfo);
             //修改用户的状态
             const {data:res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
             //  console.log(res)
             if(res.meta.status!=200){
                 userinfo.mg_state= !userinfo.mg_state
                 return this.$message.error('更新用户状态失败！！！')
             }
             this.$message.success('更新状态成功！！！')
          },
          addUser(){
            this.$refs.addFormRef.validate(async valid=>{
               if(!valid) {
                   return;
               }    
               const {data:res} =await this.$http.post('users',this.form)
               this.dialogFormVisible = false
                if(res.meta.status!=201) {
                  return this.$message.error('添加失败!')    
                }
                this.$message.success('添加成功!')
                this.getUserList() 
                console.log(res); 
           });
          },
          async del(id){
            const {data:res} = await this.$http.delete("users/"+id)
            if(res.meta.status!=200){
                 return this.$message.error('删除失败！！！')
             }
             this.$message.success('删除成功！！！')
             this.getUserList() 
          }
      }
    }
</script>

<style lang="less" scoped>
  .el-card {
    margin-top: 15px;
  }
</style>